package com.liuguang.gateway.config.sentinel;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.liuguang.common.pojo.CommonResult;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: MySentinelExceptionHandler
 * @Description： sentinel 限流和异常处理类。并且初始化 sentinel 资源
 * 1、类中的方法必须实 static 否则不能使用
 * 2、类的返回结果和参数，与原方法一致，限流处理方法可以多加：BlockException 参数，异常处理可以多加Throwable 参数
 * @Author: wanghr
 * Date: 11:10 AM 2020/11/4
 * Version: 1.0
 */
@Configuration
public class MySentinelExceptionHandler implements InitializingBean {

    public static CommonResult handleBlockException(BlockException e) {
        System.out.println("进入限流异常处理静态方法");
        return CommonResult.fail("出现限流异常，快速失败");
    }

    public static CommonResult handleException(Throwable e) {
        System.out.println("进入异常处理静态方法");
        return CommonResult.fail("出现异常，快速失败!!");
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("=====初始化 sentinel 资源===");
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("mySource1");
        // 0：线程数；1：qps，
        rule.setGrade(0);
        // Set limit QPS to 20.
        rule.setCount(1);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}
